package com.example.myapplication.ui.home;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapplication.ui.notifications.LoginBean;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

public class HomeViewModel extends ViewModel {
    private static final String TAG = "HomeViewModel";

    private MutableLiveData<String> mText;
    private MutableLiveData<FindHouseBean> findHouseBeanMutableLiveData=new MutableLiveData<>();

    public MutableLiveData<FindHouseBean> getFindHouseBeanMutableLiveData() {
        return findHouseBeanMutableLiveData;
    }

    // 根据houseType来访问网络获取数据，更新findHouseBeanMutableLiveData
    public void getData(Context context,String houseType){
        JSONObject jsonObject = new JSONObject();

        String url ="http://124.93.196.45:10001/prod-api/api/house/housing/list?houseType="+houseType;
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.GET,
                url,
                jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.e(TAG, "onResponse: "+jsonObject.toString() );

                        Gson gson = new Gson();
                        FindHouseBean findHouseBean = gson.fromJson(jsonObject.toString(), FindHouseBean.class);
                        findHouseBeanMutableLiveData.postValue(findHouseBean);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }

        ); // 五个参数
        requestQueue.add(request);


    }
    public HomeViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("This is home fragment");
    }

    public LiveData<String> getText() {
        return mText;
    }
}